package router

import (
	"errors"
	"gomonitor-server/src/config"
	"gomonitor-server/src/http/handler"
	"gomonitor-server/src/mylog"
	"net/http"
	"path/filepath"
)

// 验证失败
func AuthFailed(w http.ResponseWriter, errMsg string) {
	w.Header().Set("WWW-Authenticate", `Basic realm="My REALM"`)
	w.WriteHeader(401)
	w.Write([]byte(errMsg))
}

func AuthFilter(w http.ResponseWriter, r *http.Request) error {
	mylog.Logger.Debug("请求地址:" + r.RequestURI)
	user, pwd, ok := r.BasicAuth()
	if !ok {
		AuthFailed(w, "401 Unauthorized!")
		return errors.New("401 Unauthorized!")
	}
	myCfg := config.GetConfig()

	if myCfg.App.HttpUser != user || myCfg.App.HttpPassword != pwd {
		AuthFailed(w, "401 Unauthorized!")
		return errors.New("401 Unauthorized!")
	}
	return nil
}

func Router() {
	filter := NewFilter()
	var routerMap = make(map[string]func(http.ResponseWriter, *http.Request))
	routerMap["/gomonitor/api/host_tag/add"] = handler.HostAddTagHandler
	routerMap["/gomonitor/api/host_tag/delete"] = handler.HostDeleteTagHandler
	routerMap["/gomonitor/api/host/delete"] = handler.HostDeleteHandler
	routerMap["/gomonitor/test"] = handler.TestHandler

	filter.RegisterFilterUri("/*", AuthFilter)
	for key, v := range routerMap {
		http.HandleFunc(key, filter.Handle(v))
	}

	staticDir, _ := filepath.Abs("./src/static")
	fsh := http.FileServer(http.Dir(staticDir))
	http.Handle("/gofile/static/", http.StripPrefix("/gofile/static/", fsh))

}
